/* js for preference page */

$(document).ready(function() {
    var queryCounter = 0;
    var prefHome, prefAvatar;
    var placeMarkers = [];
    var map, homeMarker, options, center, lastZoomLevel;
    var homeLatitude, homeLongitude, homeLatLng;
    var lastLatitude, lastLongitude, lastLatLng;

    $.ajaxSetup({
        beforeSend:function(xhr, settings) {
          if (!utils.safeMethod(settings.type) && utils.sameOrigin(settings.url)) {
            xhr.setRequestHeader("X-CSRFToken", utils.readCookie('csrftoken'));
          }
        }
    });

    homeLatitude = utils.readCookie('homeLatitude');
    homeLongitude = utils.readCookie('homeLongitude');
    homeLatLng = new google.maps.LatLng(homeLatitude, homeLongitude);

    function autoFill(results) {
      $('#pref-geocode-query').css({'color':'#1a1a1a'});

      var country, region, city, district, plate, address,
        formatted_address = results[0].formatted_address,
        address_components = results[0].address_components;
        ///var address = address_components[1].long_name + address_components[0].long_name;

        //console.log(results[0]);
        ///var address = address_components[1].long_name + address_components[0].long_name;

        //document.getElementById('id_address').value = formatted_address;
        //if (address_components.length >= 6) {
        if (results[0].geometry.location_type === 'ROOFTOP') {
          country = address_components[5].long_name;
          region = address_components[4].long_name;
          city = address_components[3].long_name;
          district = address_components[2].long_name;
          plate = address_components[1].long_name;

          //document.getElementById('id_country').value = address_components[5].long_name;
          //document.getElementById('id_region').value = address_components[4].long_name;
          //document.getElementById('id_city').value = address_components[3].long_name;
          //document.getElementById('id_district').value = address_components[2].long_name;
          //} else if (address_components.length == 5) {
        } else if (results[0].geometry.location_type === 'RANGE_INTERPOLATED') {
          country = address_components[5].long_name;
          region = address_components[4].long_name;
          city = address_components[3].long_name;
          district = address_components[2].long_name;
          plate = address_components[1].long_name;

          //document.getElementById('id_country').value = address_components[5].long_name;
          //document.getElementById('id_region').value = address_components[4].long_name;
          //document.getElementById('id_city').value = address_components[3].long_name;
          //document.getElementById('id_district').value = address_components[2].long_name;
        } else if (results[0].geometry.location_type === 'GEOMETRIC_CENTER') {
          country = address_components[4].long_name;
          region = address_components[3].long_name;
          city = address_components[2].long_name;
          district = address_components[0].long_name;
          plate = address_components[1].long_name;

          //document.getElementById('id_country').value = address_components[4].long_name;
          //document.getElementById('id_region').value = address_components[3].long_name;
          //document.getElementById('id_city').value = address_components[2].long_name;
          //document.getElementById('id_district').value = address_components[1].long_name;
        } else if (results[0].geometry.location_type === 'APPROXIMATE') {
          country = address_components[4].long_name;
          region = address_components[3].long_name;
          city = address_components[2].long_name;
          district = address_components[1].long_name;
          plate = address_components[0].long_name;

          //document.getElementById('id_country').value = address_components[4].long_name;
          //document.getElementById('id_region').value = address_components[3].long_name;
          //document.getElementById('id_city').value = address_components[2].long_name;
          //document.getElementById('id_district').value = address_components[1].long_name;
        }

        document.getElementById('pref-geocode-query').value = country + region + city + district + plate;
    }

    function autoMove(results) {
      if (!results[0]) {
        document.getElementById('pref-geocode-query').value = '请再试一次';
      } else {
        var location = results[0].geometry.location;

        homeMarker.setPosition(location);
        map.setCenter(location);
        utils.writeLatLng(location.lat(), location.lng());
      }
    }

    function createPrefAvatar() {
    }

    function removePrefAvatar() {
    }

    function createPrefHome() {
      center = homeLatLng;
      lastZoomLevel = parseInt(utils.readCookie('lastZoomLevel'), 10) || 10;

      options = {
        center: center,
        zoom: lastZoomLevel,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true,
        navigationControl: true,
        navigationControlOptions: {
          position: google.maps.ControlPosition.RIGHT_BOTTOM,
          style: google.maps.NavigationControlStyle.SMALL
        }
      };

      map = new google.maps.Map(document.getElementById('map-home'), options);

      var control = document.createElement('div');
      //control.id = 'button-home';
      //control.style.position = 'absolute';
      //control.style.top = '10px';
      //control.style.right = '10px';
      control.innerHTML = '<img src="/static/img/map/home.png" width="50" height="50" />';
      //control.index = 1;

      // Add the control to the map
      map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);

      // When the button is clicked pan to sydney
      google.maps.event.addDomListener(control, 'click', function() {
          console.log('back to home');
          map.setCenter(homeLatLng);
          homeMarker.setPosition(homeLatLng);
          lastLatitude = homeLatitude;
          lastLongitude = homeLongitude;
          utils.createCookie('lastLatitude', lastLatitude);
          utils.createCookie('lastLongitude', lastLongitude);    
          //map.panTo(homeLatLng);
      });                        

      google.maps.event.addListener(map, 'zoom_changed', function() {
          var zoomLevel = map.getZoom();
          utils.createCookie('lastZoomLevel', zoomLevel, 365);
          console.log('lastZoomLevel: ' + zoomLevel);
      });

      homeMarker = gmap.createHomeMarker(map, lastLatLng || homeLatLng);

      //utils.writeLatLng(lastLatitude || homeLatitude, lastLongitude || homeLongitude);

      console.log('map has been created!');
      google.maps.event.addListener(homeMarker, 'dragend', function() {
          homeMarker.setOptions({icon: gmap.homeMarker});
          var homeLatLng = homeMarker.getPosition();
          var expires = new Date(Date.now() + gmap.ONE_DAY * 365).toUTCString();
          homeLatitude = homeLatLng.lat();
          homeLongitude = homeLatLng.lng();
          console.log('homeLatidue: ' + homeLatitude);
          console.log('homeLongitude: ' + homeLongitude);
          console.log('start set cookie');
          console.log('end set cookie');
          map.setCenter(homeLatLng);

          //utils.writeLatLng(homeLatitude, homeLongitude);

          // Call geocode
          if ($('input#from-location-to-address:checked').val()) {
            gmap.geocode({'latLng': homeLatLng}, autoFill);
          }
      });
    }

     // From address get location information
      $('input#pref-geocode-query').change(function() {
        //setTimeout(function() {
          var address = $(this).val();
          console.log(address);
          if ($('input#from-address-to-location:checked').val()) {
            gmap.geocode({'address':address}, autoMove);
          }
         // }, 800);
      });                                                  

    function removePrefHome() {
      $('div#map-home').html('');
    }
    //lastLatitude = utils.readCookie('lastLatitude') || homeLatitude;
    //lastLongitude = utils.readCookie('lastLongitude') || homeLongitude;
    //lastLatLng = new google.maps.LatLng(lastLatitude, lastLongitude);

    // page init
    $('#form-pref-avatar').hide(function() {
       prefAvatar = false;
     });
    $('div#pref-home').hide(function() {
        prefHome = false; 
    });

    // event
    $('input#from-location-to-address').change(function() {
          $('span#from-location-to-address-text').css({'color':'#000'});
          $('span#from-address-to-location-text').css({'color': '#ccc'});
      });

      $('input#from-address-to-location').change(function() {
          $('span#from-address-to-location-text').css({'color': '#000'});
          $('span#from-location-to-address-text').css({'color': '#ccc'});  
      });                                  

    $('#pref-avatar-trigger').click(function() {
        var trigger = this;
        if (!prefAvatar) {
          $('#form-pref-avatar').slideDown('slow', function() {
              $('#pref-avatar').show();
              $(trigger).html('^');
              prefAvatar = true;
          });
        } else {
          $('#form-pref-avatar').slideUp('slow', function() {
              $('#pref-avatar').hide();
              $(trigger).html('v');
              prefAvatar = false;
          });
        }
    });

    $('#pref-home-trigger').click(function() {
        var trigger = this;
        if (!prefHome) {
          $('#pref-home').slideDown('slow', function() {
              createPrefHome();
              $(trigger).html('^');
              prefHome = true;
          });
        } else {
          $('#pref-home').slideUp('slow', function() {
              removePrefHome();
              $(trigger).html('v');
              prefHome = false;
          });
        }
    });

    $('input#pref-geocode-query').keyup(function() {
        var address = $(this).val();
        if (this.timer) { clearTimeout(this.timer);}
        this.timer = setTimeout(function() {
            gmap.geocode({'address':address}, autoMove);
          }, 3000);
    });

    $('input#pref-geocode-query').click(function() {
        $(this).val('');
        $(this).css({'color':'#1a1a1a'});

        $(this).unbind('click');
    });

    $('#button-home').click(function() {
        console.log('back to home');
        map.setCenter(homeLatLng);
        homeMarker.setPosition(homeLatLng);
        lastLatitude = homeLatitude;
        lastLongitude = homeLongitude;
        utils.createCookie('lastLatitude', lastLatitude);
        utils.createCookie('lastLongitude', lastLongitude);
    });

    $('#submit-pref-home').click(function() {
        popup.create();

        var csrfToken = utils.readCookie('csfrtoken');

        this.timer = setTimeout(function() {
            $.ajax({
                url:'/action/preference/home/',
                data: 'homeLatitude='+homeLatitude+'&homeLongitude='+homeLongitude,
                dataType: 'json',
                type: 'post',
                error:function() {
                  popup.disable('Error');
                },
                success:function (results) {
                  if (results.ok) {
                    popup.disable('Success');
                    utils.createCookie('homeLatitude', homeLatitude);
                    utils.createCookie('homeLongitude', homeLongitude);
                  } else {
                    popup.disable('Failed');
                  }
                }
            });                                                                                                        
          },
          // Set timeout 
          // to 2 seconds
          2000);
    });                                        

    /*
    $("input#submit-pref-avatar").click(function() {
        popup.create();
        var src='/avatar/';
        var filename = $("#id_avatar").val();

        if (this.timer) { clearTimeout(this.timer); }
        this.timer = setTimeout(function() {
            $.ajax({ 
                type: "post",
                url: "/action/preference/avatar/",
                dataType: 'json',
                enctype: 'multipart/form-data',
                data: {avatar: filename},
                error: function() {
                  popup.disable('error');
                },
                success: function(results){
                  if (results.ok) {
                    src += results.grid_id;
                    popup.disable('Success');
                    $('#people-avatar').attr('src', src);
                  } else {
                    popup.disable('Failed');
                  }
                }
            });     
          }, 2000);
    });*/
});
